package com.tianji.learning.service.impl;

import com.tianji.common.utils.CollUtils;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

/**
 * @author Covey
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PointsBoardAsyncService {

    private final RedisTemplate<String, String> redisTemplate;

    @Async("cacheTaskExecutor")
    public void asyncWriteToRedis(String key, List<PointsBoard> records, Integer seasonId) {
        try {
            if (CollUtils.isEmpty(records)) {
                return;
            }
            // 使用Pipeline批量操作
            redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
                for (PointsBoard p : records) {
                    if (p.getUserId() != null && p.getPoints() != null) {
                        connection.zSetCommands().zAdd(
                                key.getBytes(),
                                p.getPoints().doubleValue(),
                                String.valueOf(p.getUserId()).getBytes()
                        );
                    }
                }
                // 设置过期时间
                connection.expire(key.getBytes(),
                        Duration.ofHours(RedisConstants.REDIS_EXPIRE_TIME_HOURS).getSeconds());
                return null;
            });
            log.info("异步Pipeline写入Redis成功，赛季{}，记录数{}", seasonId, records.size());
        } catch (Exception e) {
            log.error("异步写入Redis失败，赛季{}", seasonId, e);
        }
    }
}